package com.net.netmonitor.util;

import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

//使用iperf工具，调用dmc命令，来检测客户端与服务器段的网速
public class IperfUtil {

    //保留2位小数
    private static DecimalFormat df = new DecimalFormat("#.00");

    private static String netSec="";//最终返回的结果
    private static String ip = "";//服务器ip
    private static String port = "";//服务器端监听的端口

    public static String getNetSpeed() throws Exception{

        //当前项目jar包所在目录
        String ROOT = PropertiesFileUtil.getRootPath();

        //从配置文件获取ip和port的值
        String filePath = ROOT + "\\serverInfo.properties";
        ip = PropertiesFileUtil.getValueByKey("ip",filePath);
        port = PropertiesFileUtil.getValueByKey("port",filePath);

        //构造出要执行的命令，检测10s，间隔2s，以MB作为单位
        String cmd =  ROOT + "\\jperf-2.0.0\\bin\\iperf -c "+ip+" -p "+port+" -i 2 -t 10 -f M";

        Process p = Runtime.getRuntime().exec(cmd);

        InputStream inputStream = p.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        double count = 0;//带宽总量
        int second = 0;//查询带宽次数
        while((line = reader.readLine())!= null){
            //[312]  0.0-10.0 sec  2.46 GBytes  2.11 Gbits/sec
            if(line.contains("/sec")){//获取到宽带信息，从“Bytes”开始截取，到“/sec”结束
                netSec = line.substring(line.indexOf("Bytes")+5,line.indexOf("MBytes/sec")).trim();
                count += Double.parseDouble(netSec);
                second ++;

                System.out.println(line);
            }
        }

        //求平均数
        netSec = df.format(count/second);
        System.out.println("平均网速："+netSec);

        p.waitFor();
        inputStream.close();
        reader.close();
        p.destroy();
        return netSec;
    }
}
